package cn.datawin.cmppprovider.handler.cmpp;

import cn.datawin.cmppprovider.task.DelayQueueManager;
import cn.datawin.cmppprovider.task.DelayTask;
import cn.datawin.cmppprovider.util.RandUtil;
import cn.datawin.cmppprovider.util.SpringContextUtil;
import com.drondea.sms.channel.ChannelSession;
import com.drondea.sms.common.util.CommonUtil;
import com.drondea.sms.common.util.MsgId;
import com.drondea.sms.message.cmpp.CmppSubmitRequestMessage;
import com.drondea.sms.message.cmpp.CmppSubmitResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ServerCmppSubmitRequestHandler extends SimpleChannelInboundHandler<CmppSubmitRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CmppSubmitRequestMessage msg) throws Exception {
        log.debug("cmpp submit request {}-{}", msg.getDestTerminalId()[0], msg.getMsgContent());
        ChannelSession channelSession = CommonUtil.getChannelSession(ctx.channel());
        MsgId msgId = new MsgId(channelSession.getSequenceNumber());
        CmppSubmitResponseMessage response = new CmppSubmitResponseMessage(msg.getHeader());
        response.setMsgId(msgId);
        response.setResult(0);
        channelSession.sendMessage(response);

        String s = msg.getDestTerminalId()[0];
        SpringContextUtil.getBean(DelayQueueManager.class).put(new DelayTask(channelSession, msgId, s, getRandomTime(s), 1, msg.getSrcId()));
    }

    private int getRandomTime(String s) {

//        int a = random.nextInt(100);
//        if (a < 95) {
//            return (3 + RandUtil.random.nextInt(6)) * 1000;
//        }
//        log.info("超时数据-----{}",s);
//        return (6*60 + RandUtil.random.nextInt(8*60)) * 1000;
        return (3 + RandUtil.random.nextInt(6)) * 1000;
    }
//    private int getRandomTime() {
//        return 30 * 1000;
//    }
}
